package org.testis.communication.client;

import java.io.IOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

/**
 * A class to create a client over UDP.
 * @author nurhat
 */
public class AtofUdpClient {

    private DatagramSocket clientSocket;
    private int m_keepAliveTime;
    private int m_portNumber;
    private String m_ipAddress;
    private String m_stringToSend;
    private StringBuilder m_lastError;

    /**
     * Creates telnet client
     * @param keepAliveTime
     * @param portNumber
     * @param ipAddress
     * @param stringToSend
     */
    public AtofUdpClient(int keepAliveTime,
            int portNumber,
            String ipAddress,
            String stringToSend) {
        m_keepAliveTime = keepAliveTime;
        m_portNumber = portNumber;
        m_ipAddress = ipAddress;
        m_stringToSend = stringToSend;
        m_lastError = new StringBuilder();
    }

    /**
     * Binds to server over given parameters.
     * Send a message to server and wait for the server result
     * @return answer of server
     * @throws java.io.IOException
     */
    public String waitForServerMessage() {

        String result = null;
        try {
            clientSocket = new DatagramSocket();
            clientSocket.setSoTimeout(m_keepAliveTime);
            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];

            sendData = m_stringToSend.getBytes("UTF-8");
            InetAddress serverAddr = InetAddress.getByName(m_ipAddress);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddr, m_portNumber);
            clientSocket.send(sendPacket);

            DatagramPacket recievePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(recievePacket);
            result = new String(recievePacket.getData(), "UTF-8");
            result = result.substring(0, recievePacket.getLength());
        } catch (ConnectException ex) {
            m_lastError.append("No server found on given ip port[" + m_ipAddress + "," + m_portNumber + "]. Client couldnt connected to server");
        }  catch (SocketTimeoutException ex) {
            m_lastError.append("No server found on given ip port[" + m_ipAddress + "," + m_portNumber + "]. Client couldnt connected to server");
        } catch (Exception ex) {
            m_lastError.append(ex.toString());
        } finally {

            if (clientSocket != null) {
                clientSocket.close();
            }

        }
        return result;
    }

    /**
     * @return the m_lastError
     */
    public String getLastError() {
        return m_lastError.toString();
    }
}
